package com.mamesoft.medicipazienti.servlet;

import com.mamesoft.medicipazienti.tools.JDBC;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.ResultSet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class DettaglioPazienteServlet extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    private static Logger log = Logger.getLogger(DettaglioPazienteServlet.class);

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        PropertyConfigurator.configure(DettaglioPazienteServlet.class.getClassLoader().getResource("com/mamesoft/medicipazienti/tools/log4j.properties"));

        Connection connect = null;
        PrintWriter out = null;
        try {

            response.setContentType("text/html;charset=UTF-8");
            String idPaziente = request.getParameter("id");
            HttpSession session = request.getSession();
            connect = JDBC.connect();
            DateFormat d = DateFormat.getDateInstance();
            out = response.getWriter();

            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("    <head>");
            out.println("        <title>Vaccino Manger</title>");
            out.println("        <link rel=\"stylesheet\" type=\"text/css\" href=\"/MediciPazienti/variant-stream.css\" title=\"Variant Stream\" media=\"screen,projection\" />");
            out.println("        <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">       ");
            out.println("    </head>");

            out.println("    <body>");
            out.println("        <div id =\"wrap\">");
            out.println("            <div id=\"header\">");
            out.println("                <div id =\"topmenu\">");
            out.println("                    <p>");
            out.println("                        <a href=\"/MediciPazienti/logout\">Logout</a>");
            out.println("                    </p>");
            out.println("                </div>");
            out.println("                <div id=\"title\">");
            out.println("                    <h1>Vaccino Manager</h1><br/>");
            out.println("                    <h2 class =\"slogan\">I tuoi vaccini contano</h2>");
            out.println("                </div>");
            out.println("            </div>");

            out.println("            <div id=\"sidebar\">");
            out.println("               <ul class = \"sidemenu\">");
            out.println("                   <li><a href=\"/MediciPazienti/medico/welcome\">Home</a><li>");
            out.println("                   <li><a href=\"/MediciPazienti/medico/richiama\">Invia richiami</a><li>");
            out.println("                   <li><a href=\"/MediciPazienti/medico/visualizza_storico\">Visualizza Storico</a><li>");
            out.println("                   <li><a href=\"/MediciPazienti/logout\">Logout</a><li>");
            out.println("               </ul>");
            out.println("            </div>");

            out.println("            <div id =\"content\">");
            out.println("                <div id=\"feature\">");
            out.println("                    <p>" + session.getAttribute("last_login") + "</p>");
            out.println("                    </p>");
            out.println("                </div>");
            out.println("                <div class=\"post\">");


            String query = "SELECT Nome,Cognome,Data,Foto FROM paziente "
                    + "WHERE id =\"" + idPaziente + "\"";
            ResultSet set = JDBC.executeQuery(query, connect);
            if (set.next()) {

                Timestamp t = set.getTimestamp("Data");
                Date date = new Date(t.getTime());
                out.println("<table border=\"0\">");
                out.println("<tr>");
                out.println("  <td rowspan=\"3\"><img src=\"/MediciPazienti" + set.getString("Foto").replace("jpg", "JPG") + "\"  alt=\"Foto\"/></td>");
                out.println("  <td>Nome:</td>");
                out.println("  <td>" + set.getString("Nome").toUpperCase() + "</td>");
                out.println("</tr>");
                out.println("<tr>");
                out.println("  <td>Cognome:</td>");
                out.println("  <td>" + set.getString("Cognome").toUpperCase() + "</td>");
                out.println("");
                out.println("</tr>");
                out.println("<tr>");
                out.println("  <td>Data di nascita:</td>");
                out.println("  <td>" + d.format(date) + "</td>");
                out.println("");
                out.println("</tr>");
                out.println("</table>");
                set.close();
                query = "SELECT vaccino.data AS Data, medico.nome AS NomeMedico, medico.cognome AS CognomeMedico,"
                        + " paziente.nome AS NomePaziene, paziente.cognome AS CognomePaziente "
                        + "FROM vaccino JOIN medico ON ( vaccino.mID = medico.ID ) "
                        + "JOIN paziente ON ( vaccino.pID = paziente.ID ) "
                        + "WHERE paziente.id =\"" + idPaziente + "\" "
                        + "ORDER BY Data DESC;";
                set = JDBC.executeQuery(query, connect);
                if (set.next()) {
                    out.println("<table border=\"0\" cellspacing=\"0\">");
                    out.println("    <thead>");
                    out.println("        <tr>");
                    out.println("            <th>DATA <br/> VACCINAZIONE</th>");
                    out.println("            <th>MEDICO</th>");
                    out.println("        </tr>");
                    out.println("    </thead>");
                    do {
                        Date time = set.getTimestamp("Data");
                        String nomeMedico = set.getString("NomeMedico");
                        String cognomeMedico = set.getString("CognomeMedico");
                        nomeMedico = nomeMedico.substring(0, 1).toUpperCase() + nomeMedico.substring(1).toLowerCase();
                        cognomeMedico = cognomeMedico.substring(0, 1).toUpperCase() + cognomeMedico.substring(1).toLowerCase();
                        out.println("    <tr>");
                        out.println("        <td> " + d.format(time) + "</td>");
                        out.println("        <td> Dr. " + nomeMedico + " " + cognomeMedico + " </td>");
                        out.println("    </tr>");
                    } while (set.next());
                    out.println("</tbody>");
                    out.println("</table>");
                } else {
                    out.println("Non hai effettuato vaccinazioni ad oggi");
                }
            } else {
                out.println("<p>Questo paziente...non esiste</p>");
            }

            out.println("                </div>");
            out.println("            </div>");
            out.println("            <div id=\"footer\">");
            out.println("                <p class=\"centered\">Copyright &copy; 2011 <a href=\"/MediciPazienti/index.html\">Mamesoft</a>");
            out.println("                    Progetto Programmazione per il web A.A.2011/2012</p>");
            out.println("            </div>");
            out.println("        </div>");
            out.println("    </body>");
            out.println("</html>");

        } catch (Exception ex) {
            request.getSession().invalidate();
            if (ex instanceof SQLException) {
                log.error("Database Error: " + ex.toString());
                response.sendRedirect("/MediciPazienti/database_error.html");
            } else {
                log.error("Generic error: " + ex.toString());
                response.sendRedirect("/MediciPazienti/general_error.html");
            }
        } finally {
            if (connect != null) {
                try {
                    connect.close();
                } catch (SQLException ex) {
                    request.getSession().invalidate();
                    log.error("Database Error: " + ex.toString());
                    response.sendRedirect("/MediciPazienti/database_error.html");
                }
            }
            if (out != null) {
                out.close();
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
